package morenoapp.components.workplace;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.EnumMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import morenoapp.MorenoApp;
import morenoapp.action.MorenoActionsFacade;
import morenoapp.components.common.LinkLabel;
import morenoapp.util.I18N;
import morenoapp.util.MorenoUtil;

/**
 *
 * @author dmitry.mamonov
 */
public class WizardPanel extends JPanel {
    WorkplaceNavigator navigator;
    JPanel navigatePanel = new JPanel();
    EnumMap<WorkplaceView, LinkLabel> viewsMap = new EnumMap<WorkplaceView, LinkLabel>(WorkplaceView.class);

    JTextPane helpText = new JTextPane();
    JScrollPane helpScrollPane = new JScrollPane(helpText);
    {
        helpScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        helpScrollPane.getVerticalScrollBar().setUnitIncrement(4);
        helpScrollPane.setBackground(Color.WHITE);
        helpText.setContentType("text/html");
        helpText.setText("<html>");
        helpText.setEditable(false);
        helpScrollPane.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                helpText.setPreferredSize(new Dimension(e.getComponent().getWidth(),helpText.getHeight()*2));
                helpText.setSize(helpText.getPreferredSize());
            }
        });
        helpText.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(HyperlinkEvent e) {
                if (e.getEventType()==HyperlinkEvent.EventType.ACTIVATED){
                    if (e.getDescription().startsWith("http://")){
                        try {
                            Desktop.getDesktop().browse(e.getURL().toURI());
                        } catch (URISyntaxException ex) {
                            Logger.getLogger(WizardPanel.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (IOException ex) {
                            Logger.getLogger(WizardPanel.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else if (e.getDescription().startsWith("mailto:")){
                        try {
                            Desktop.getDesktop().mail(e.getURL().toURI());
                        } catch (URISyntaxException ex) {
                            Logger.getLogger(WizardPanel.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (IOException ex) {
                            Logger.getLogger(WizardPanel.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        JComponent component = MorenoUtil.findComponentByName(MorenoApp.getApplication().getMainView().getComponent(), e.getDescription());
                        if (component!=null && component.isVisible()){
                            MorenoUtil.surroundComponent(component);
                        }
                    }
                }
            }
        });
    }

    public WizardPanel(WorkplaceNavigator _navigator) {
        super(new BorderLayout());
        this.navigator = _navigator;
        add(navigatePanel, BorderLayout.NORTH);
        add(helpScrollPane, BorderLayout.CENTER);
        setBackground(Color.WHITE);

        //help panel
        //TitledBorder helpTitledBorder = new TitledBorder(I18N.get("wizard_panel.help"));
        //helpTitledBorder.setTitlePosition(TitledBorder.TOP);
        //helpTitledBorder.setBorder(new EmptyBorder(0, 0, 0, 0));
        //helpScrollPane.setBorder(helpTitledBorder);
        helpScrollPane.setBorder(null);
        
        //navigation panel
        TitledBorder navigateTitledBorder = new TitledBorder("  "+I18N.get("wizard_panel.navigation_title")+"  ");
        navigateTitledBorder.setTitlePosition(TitledBorder.TOP);
        //titledBorder.setBorder(LineBorder.createGrayLineBorder());
        //titledBorder.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
        navigatePanel.setBorder(navigateTitledBorder);
        navigatePanel.setName("panelNavigation");
        //navigatePanel.setBackground(new Color(0xf4f3f3));
        //navigatePanel.setBackground(new Color(0xF8C04B));
        //navigatePanel.setBackground(new Color(194,203,215));
        navigatePanel.setBackground(Color.WHITE);
        navigatePanel.setLayout(new BoxLayout(navigatePanel, BoxLayout.PAGE_AXIS));
        for (final WorkplaceView view : WorkplaceView.values()) {
            if (view.ordinal()>0){
                navigatePanel.add(createSpacer(3));
            }
            final LinkLabel linkLabel = new LinkLabel();
            linkLabel.setText(String.format("%1$d. %2$s", view.ordinal() + 1, view.getCaption()));
            linkLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
            linkLabel.setHighlightBackground(true);
            linkLabel.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    navigator.activateView(view);
                }
            });
            viewsMap.put(view, linkLabel);
            
            navigatePanel.add(linkLabel);
        }
        { //prev-next buttons
            JSeparator separator = new JSeparator(JSeparator.HORIZONTAL);
            separator.setForeground(Color.GRAY);
            separator.setMaximumSize(new Dimension(350, 4));
            separator.setPreferredSize(separator.getMaximumSize());

            JPanel panelBottom = new JPanel(new FlowLayout(FlowLayout.LEFT));
            panelBottom.setBackground(navigatePanel.getBackground());
            panelBottom.setAlignmentX(Component.LEFT_ALIGNMENT);

            LinkLabel linkLabelPrev = new LinkLabel();
            linkLabelPrev.setHighlightBackground(true);
            linkLabelPrev.setAction(MorenoActionsFacade.getActionNavigatePrev());
            panelBottom.add(linkLabelPrev,BorderLayout.WEST);

            JLabel labelSeparator = new JLabel("   |   "); //NOI18N
            labelSeparator.setForeground(separator.getForeground());
            panelBottom.add(labelSeparator);

            LinkLabel linkLabelNext = new LinkLabel();
            linkLabelNext.setHighlightBackground(true);
            linkLabelNext.setAction(MorenoActionsFacade.getActionNavigateNext());
            linkLabelNext.setHorizontalTextPosition(SwingConstants.LEFT);
            panelBottom.add(linkLabelNext);

            navigatePanel.add(createSpacer(7));
            navigatePanel.add(separator);
            navigatePanel.add(panelBottom);
        }
        //navigatePanel.add(createSpacer(10));
        navigator.addNavigatorListener(new WorkspaceNavigatorListener() {
            @Override
                public void onSelectedView(WorkplaceView selectedView) {
                    for(Map.Entry<WorkplaceView,LinkLabel> entry:viewsMap.entrySet()){
                        if (entry.getKey()==selectedView){
                            entry.getValue().setSelected(true);
                        } else {
                            if (entry.getValue().isSelected()){
                                entry.getValue().setSelected(false);
                            }
                        }
                    }
                    //update help text
                    String helpHtml = selectedView.getHelp();
                    int pos = 0;
//                    pos = helpHtml.indexOf("morena.color.application");
//                    helpHtml = helpHtml.replace("morena.color.application", "red");
//                    System.out.println(helpHtml);
                    helpText.setText(helpHtml);
                    helpText.setCaretPosition(pos>=0?pos:0);
                }
            });
    }

    private JPanel createSpacer(int height) {
        JPanel spacer = new JPanel();
        spacer.setPreferredSize(new Dimension(1, height));
        spacer.setOpaque(false);
        return spacer;
    }
}
